<script setup lang="ts">
import { reactive, watch, ref, nextTick, onBeforeUnmount } from 'vue'
import useCategoryStore from '@/store/modules/category'
import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr'
import type { AttrResponseData, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
const categoryStore = useCategoryStore()

let attrArr = ref<Attr[]>([])
//定义card组件内容切换变量
//scene=0,显示table,scene=1,展示添加与修改属性结构
let scene = ref<number>(0)

let inputArr = ref<any>([])

let attrParams = reactive<Attr>({
  attrName: '', //新增的属性的名字
  attrValueList: [
    //新增的属性值数组
  ],
  categoryId: '', //三级分类的ID
  categoryLevel: 3, //代表的是三级分类
})
//监听仓库三级分类ID变化
watch(
  () => categoryStore.c3Id,
  () => {
    //清空上一次查询的属性与属性值
    attrArr.value = []
    //保证三级分类得有才能发请求
    if (!categoryStore.c3Id) return
    //调用获取分类的ID
    getAttr()
  },
)
//获取已有的属性与属性值方法
const getAttr = async () => {
  const { c1Id, c2Id, c3Id } = categoryStore
  //获取分类下的已有的属性与属性值
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
  if (result.code === 200) {
    attrArr.value = result.data
  }
}

// 添加回调
const arrAttr = () => {
  //每一次点击的时候,先清空一下数据再收集数据
  Object.assign(attrParams, {
    attrName: '', //新增的属性的名字
    attrValueList: [
      //新增的属性值数组
    ],
    categoryId: categoryStore.c3Id, //三级分类的ID
    categoryLevel: 3, //代表的是三级分类
  })
  //切换为添加与修改属性的结构
  scene.value = 1
  // attrParams.categoryId = categoryStore.c3Id
}
// 编辑回调
const updateAttr = (row: Attr) => {
  //将已有的属性对象赋值给attrParams对象即为
  //ES6->Object.assign进行对象的合并
  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
  //切换为添加与修改属性的结构
  scene.value = 1
}
// 删除回调
const deleteAttr = async (attrId: number) => {
  const result = await reqDeleteAttr(attrId)

  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
//取消
const cancel = () => {
  scene.value = 0
}

const addAttrValue = () => {
  //点击添加属性值按钮的时候,向数组添加一个属性值对象
  attrParams.attrValueList.push({
    valueName: '',
    flag: true, //控制每一个属性值编辑模式与切换模式的切换
  })
  //获取最后el-input组件聚焦
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

const save = async () => {
  const result = await reqAddOrUpdateAttr(attrParams)
  if (result.code === 200) {
    scene.value = 0
    ElMessage({
      type: 'success',
      message: attrParams.id ? '修改成功' : '添加成功',
    })
    getAttr()
  } else {
    ElMessage({
      type: 'error',
      message: attrParams.id ? '修改失败' : '添加失败',
    })
    getAttr()
  }
}

const toLook = (row: AttrValue, $index: number) => {
  // 1
  if (row.valueName.trim() === '') {
    //删除对应属性值为空的元素
    attrParams.attrValueList.splice($index, 1)
    // 提示信息
    ElMessage({
      type: 'error',
      message: '属性值不能为空',
    })
    return
  }

  // 2
  let repeat = attrParams.attrValueList.find((item) => {
    //切记把当前失却焦点属性值对象从当前数组扣除判断
    if (item != row) {
      return item.valueName === row.valueName
    }
  })

  if (repeat) {
    //将重复的属性值从数组当中删除
    attrParams.attrValueList.splice($index, 1)
    ElMessage({
      type: 'error',
      message: '属性值不能重复',
    })
    return
  }
  // 相应的属性值对象flag:变为false,展示div
  row.flag = false
}

const toEmit = (row: AttrValue, $index: number) => {
  //nextTick:响应式数据发生变化,获取更新的DOM(组件实例)
  nextTick(() => {
    inputArr.value[$index].focus()
  })
  //相应的属性值对象flag:变为true,展示input
  row.flag = true
}
//路由组件销毁的时候，把仓库分类相关的数据清空
onBeforeUnmount(() => {
  //清空仓库的数据
  categoryStore.$reset()
})
</script>
<template>
  <div>
    <el-card class="tall_top">
      <Category :scene="scene"></Category>
    </el-card>
    <el-card>
      <div v-if="scene === 0">
        <el-button type="primary" size="default" icon="Plus" @click="arrAttr">
          添加属性
        </el-button>
        <el-table :data="attrArr" border style="width: 100%; margin-top: 10px">
          <el-table-column
            prop="date"
            label="序号"
            type="index"
            align="center"
            width="80"
          />
          <el-table-column prop="attrName" label="属性名称" width="120" />
          <el-table-column prop="name" label="属性值名称">
            <template #="{ row }">
              <el-tag
                style="margin: 5px"
                v-for="item in row.attrValueList"
                :key="item.id"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                icon="Edit"
                @click="updateAttr(row)"
              ></el-button>
              <el-popconfirm
                :title="`您确定要删除${row.attrName}?`"
                width="200px"
                icon="Delete"
                @confirm="deleteAttr(row.id)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="small"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="scene === 1">
        <el-form :inline="true">
          <el-form-item label="属性名称">
            <el-input
              v-model="attrParams.attrName"
              placeholder="请输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          :disabled="attrParams.attrName ? false : true"
          @click="addAttrValue"
          type="primary"
          size="default"
          icon="Plus"
        >
          添加属性值
        </el-button>
        <el-button size="default" @click="cancel">取消</el-button>

        <el-table border style="margin: 10px" :data="attrParams.attrValueList">
          <el-table-column
            label="序号"
            width="80px"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                v-if="row.flag"
                :ref="(re: any) => (inputArr[$index] = re)"
                @blur="toLook(row, $index)"
                v-model="row.valueName"
                placeholder="请输入属性名称"
              ></el-input>
              <div v-else @click="toEmit(row, $index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="130px" align="center">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="small"
                @click="toEmit(row, $index)"
                icon="Edit"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                @click="attrParams.attrValueList.splice($index, 1)"
                icon="Delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-button
          :disabled="attrParams.attrValueList.length > 0 ? false : true"
          type="primary"
          size="default"
          icon="Plus"
          @click="save"
        >
          保存
        </el-button>
        <el-button size="default" @click="cancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>
<style scoped lang="scss">
.tall_top {
  margin-bottom: 10px;
}
</style>
